<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import * as userApi from '@/api/user'
import { message } from 'ant-design-vue'
import pdrLogo from '@/assets/pdr-logo.png'
import lpLogo from '@/assets/lp-logo.png'
import { useBrandStore } from '@/store/modules/brand'
const brandStore = useBrandStore()
const router = useRouter()
const userStore = useUserStore()
const myState = reactive({
  smsSendFlag: false,
  time: 60,
})

const levelNames = ref({
  0: '低',
  1: '低',
  2: '中',
  3: '强',
})
const levelClass = ref({
  0: 'error',
  1: 'error',
  2: 'warning',
  3: 'success',
})
const levelColor = ref({
  0: '#ff0000',
  1: '#ff0000',
  2: '#ff7e05',
  3: '#1890ff',
})
const passwordLevel = ref(0)
const passwordLevelChecked = ref(false)
const percent = ref(10)
const progressColor = ref('#FF0000')
// 获取验证码
const getSms = async () => {
  loginForm.value?.validateFields(['userName']).then(async () => {
    let params = {
      phone: formState.value.userName,
    }
    if (params['phone'] == '') {
      message.error(`用户名不能为空~`)
      return
    }

    const hide = message.loading('验证码发送中..', 0)
    try {
      let { state, message: msg } = await userApi.sendRegSms(params)
      if (state === 200) {
        myState.smsSendFlag = true
        const interval = setInterval(() => {
          if (myState.time-- <= 0) {
            myState.time = 60
            myState.smsSendFlag = false
            clearInterval(interval)
          }
        }, 1000)
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
    setTimeout(hide, 1)
  })
}

let labelCol = { span: 4 }
let loginForm = ref<HTMLElement | null>(null)
interface formState {
  userName: string | number
  userPassword: string
  confirmPassword: string
  smsCode: string | number
}
const formState = ref<formState>({
  userName: '',
  userPassword: '',
  confirmPassword: '',
  smsCode: '',
})

// 重置密码
const handleSubmit = async () => {
  const params: formState = {
    userName: formState.value.userName,
    smsCode: formState.value.smsCode,
    userPassword: formState.value.userPassword,
    confirmPassword: formState.value.confirmPassword,
  }
  let key: keyof formState
  for (key in params) {
    if (params[key] == '') {
      switch (key) {
        case 'userName':
          message.error(`用户名不能为空~`)
          return
        case 'smsCode':
          message.error(`验证码不能为空~`)
          return
        case 'userPassword':
          message.error(`密码不能为空~`)
          return
        case 'confirmPassword':
          message.error(`确认密码不能为空~`)
          return
      }
    }
  }
  try {
    const { state, message: msg } = await userApi.resetPassword(params)
    if (state === 200) {
      message.success('密码修改成功~')
      goLogin()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 返回登陆
const goLogin = () => {
  router.push({ path: '/login' })
}
const onFinish = async (values: any) => {
  const params: formState = {
    userName: formState.value.userName,
    smsCode: formState.value.smsCode,
    userPassword: formState.value.userPassword,
    confirmPassword: formState.value.confirmPassword,
  }
  try {
    const { state, message: msg } = await userApi.resetPassword(params)
    if (state === 200) {
      message.success('密码修改成功~')
      goLogin()
      let params = {
        userName: formState.value.userName,
        password: formState.value.userPassword,
      }
      await userStore.login(params)
      router.push({ path: '/' })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

//验证手机号 是否正常
const isPhoneNumber = (rule: any, value: any, callback: any) => {
  const phoneRegex = /^1[3-9]\d{9}$/ // 假设这是中国的手机号格式
  const numberGex = /^[0-9]+$/
  if (isNaN(value)) {
    callback(new Error('请输入有效的用户名！'))
  }
  if (!phoneRegex.test(value) && value && numberGex.test(value)) {
    callback(new Error('请输入有效的用户名！'))
  } else {
    callback()
  }
}
//两次密码输入是否一致
const passwordisEqual = (rule: any, value: any, callback: any) => {
  if (formState.value.userPassword !== value && formState.value.userPassword && value) {
    callback(new Error('两次输入的密码不一致！'))
  } else {
    callback()
  }
}
const passwordLevelClass = computed(() => {
  return levelClass.value[passwordLevel.value]
})
const passwordLevelName = computed(() => {
  return levelNames.value[passwordLevel.value]
})
const passwordLevelColor = computed(() => {
  return levelColor.value[passwordLevel.value]
})
const handlePasswordLevel = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback()

    // return
  }
  let level = 0

  // 判断这个字符串中有没有数字
  if (/[0-9]/.test(value)) {
    level++
  }
  // 判断字符串中有没有字母
  if (/[a-zA-Z]/.test(value)) {
    level++
  }
  // 判断字符串中有没有特殊符号
  if (/[^0-9a-zA-Z_]/.test(value)) {
    level++
  }
  passwordLevel.value = level
  percent.value = level * 30
  if (level >= 2) {
    if (level >= 3) {
      percent.value = 100
    }
    callback()
  } else {
    if (level === 0) {
      percent.value = 10
    }
    callback(new Error('密码强度不够!'))
  }
}
const handlePasswordLength = (rule: any, value: any, callback: any) => {
  if (value.length < 8 && value) {
    callback(new Error('密码至少8位,包含字母数字符号!'))
  } else if (!value) {
    callback(new Error('密码至少8位,包含字母数字符号!'))
  } else {
    callback()
  }
}

let activeTab = ref<number>(1)
const changeTab = (e: number) => {
  activeTab.value = e
  if (activeTab.value == 2) router.push({ path: '/login' })
}
</script>

<template>
  <div class="main-app">
    <div class="main-logo">
      <div class="lp-logo" v-if="brandStore.title_1">
        <img :src="brandStore.logo_1" />
        <span style="color: #6d36bb; font-weight: bolder; margin-left: 4px; font-size: 15px">
          {{ brandStore.title_1 }}
        </span>
      </div>
      <div class="vertical-line" v-if="brandStore.title_2"></div>
      <div class="pdr-logo" v-if="brandStore.title_2">
        <img :src="brandStore.logo_2" />
        <span style="color: black; font-weight: bolder; margin-left: 4px; font-size: 15px">
          {{ brandStore.title_2 }}
        </span>
      </div>
    </div>

    <div class="title-desc">
      <div style="letter-spacing: 4px">
        <i>{{ brandStore.description_1 }}</i>
      </div>
      <div style="letter-spacing: 4px">
        <i>{{ brandStore.description_2 }}</i>
      </div>
      <div style="font-weight: 400; font-size: 18px; letter-spacing: 10px">用技术为运营提效</div>
    </div>

    <div class="main-div">
      <a-form
        ref="loginForm"
        :model="formState"
        :label-col="labelCol"
        style="width: 18rem; height: 300px"
        @finish="onFinish"
      >
        <div class="tabs">
          <div class="left-box" @click="changeTab(1)">
            <div :class="{ 'password-login': activeTab === 1 }">重置密码</div>
          </div>
          <div class="right-box" @click="changeTab(2)">
            <span :class="{ 'register-account': activeTab === 2 }">密码登录</span>
          </div>
        </div>

        <a-form-item
          name="userName"
          :rules="[
            { required: true, message: '请输入用户名!' },
            { validator: isPhoneNumber, trigger: 'blur' },
          ]"
        >
          <a-input v-model:value="formState.userName" placeholder="请输入用户名" autocomplete="off">
            <template #prefix><UserOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input>
        </a-form-item>

        <a-form-item name="smsCode" :rules="[{ required: true, message: '请输入验证码!' }]">
          <a-input
            v-model:value="formState.smsCode"
            placeholder="验证码"
            autocomplete="off"
            style="width: 10rem"
          >
            <template #prefix><MailOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input>
          <a-button
            :disabled="myState.smsSendFlag"
            v-text="(!myState.smsSendFlag && '获取验证码') || `${myState.time} s`"
            @click="getSms"
            style="margin-left: 15px; border-radius: 6px"
            type="primary"
          ></a-button>
        </a-form-item>

        <a-form-item
          name="userPassword"
          :rules="[{ validator: handlePasswordLevel }, { validator: handlePasswordLength }]"
        >
          <a-input-password
            v-model:value="formState.userPassword"
            type="password"
            placeholder="密码至少8位,区分大小写!"
            autocomplete="off"
            @focus="passwordLevelChecked = true"
            @blur="passwordLevelChecked = false"
          >
            <template #prefix><LockOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input-password>
        </a-form-item>

        <div
          style="position: absolute; right: 0px; bottom: 160px; z-index: 10"
          v-if="passwordLevelChecked"
        >
          <a-popover
            v-model:open="passwordLevelChecked"
            placement="right"
            v-if="passwordLevelChecked"
          >
            <template #content>
              <div style="display: flex; justify-content: space-between">
                <div style="display: flex; align-items: center">
                  <div :class="['user-register', passwordLevelClass]" style="margin-right: 10px">
                    <span>{{ passwordLevelName }}</span>
                  </div>
                  <a-progress
                    :percent="percent"
                    :steps="3"
                    :showInfo="false"
                    :strokeColor="passwordLevelColor"
                  />
                </div>
              </div>
            </template>
          </a-popover>
        </div>

        <a-form-item
          name="confirmPassword"
          :rules="[
            { required: true, message: '请输入确认密码!' },
            { validator: passwordisEqual, trigger: 'blur' },
          ]"
        >
          <a-input-password
            v-model:value="formState.confirmPassword"
            type="password"
            placeholder="请输入确认密码"
            autocomplete="off"
          >
            <template #prefix><LockOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input-password>
        </a-form-item>

        <a-form-item>
          <div style="display: flex">
            <a-button style="flex: 1" type="primary" block html-type="submit">重置密码</a-button>
            <a
              style="display: inline-block; flex: 1; text-align: right; line-height: 32px"
              @click="goLogin"
            >
              返回登录界面
            </a>
          </div>
        </a-form-item>
      </a-form>
    </div>
  </div>
  <div class="footer-text">
    <a>
      {{ brandStore.recordNumber }}
    </a>
  </div>
</template>

<style scoped lang="less">
.footer-text {
  position: fixed;
  bottom: 10px;
  left: 0;
  height: 50px;
  line-height: 50px;
  width: 100%;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.user-register {
  &.error {
    color: #ff0000;
  }

  &.warning {
    color: #ff7e05;
  }

  &.success {
    color: #1890ff;
  }
}

.main-app {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('@/assets/pdr-bg.png');
  background-size: 100% 100%;
}

.main-div {
  display: flex;
  border-radius: 0.4rem;

  position: fixed;
  top: 28%;
  right: 14%;

  background: #ffffff;
  padding-top: 2rem;
  padding-bottom: 2rem;
  padding-left: 2rem;
  padding-right: 2rem;
  box-shadow: 0 10px 20px rgb(165 157 157 / 19%), 0 6px 6px rgb(255 255 255 / 23%);
}

@media (max-width: 600px) {
  /* 你可以根据需要调整这个断点 */
  .main-div {
    right: auto; /* 取消右对齐 */
    left: 50%; /* 将左边距设置为50% */
    transform: translateX(-50%); /* 向左移动自身宽度的50%，以实现居中 */
  }

  .title-desc {
    display: none;
  }
}

.main-logo {
  position: fixed;
  top: 10px;
  left: 10px;
  display: flex;
  height: 50px;
  width: 300px;
  // background: pink;

  .lp-logo {
    // width: 124px;
    flex: 1;
    height: 40px;

    img {
      height: 100%;
    }
  }

  .pdr-logo {
    flex: 1;
    height: 40px;

    img {
      height: 100%;
    }
  }

  .vertical-line {
    width: 2px; /* 竖线宽度 */
    height: 16px; /* 竖线高度，根据需要调整 */
    background-color: #999999; /* 竖线颜色，根据需要调整 */
    margin-top: 10px;
    margin-right: 28px;
  }
}

.tabs {
  display: flex;
  margin-bottom: 30px;
  font-weight: bolder;
  cursor: pointer;

  .left-box {
    flex: 1;
    text-align: right;
    padding-right: 1rem;
  }
  .right-box {
    flex: 1;
    padding-left: 1rem;
  }
}

.password-login {
  // 设置相对定位，以便伪元素可以相对于它定位
  position: relative;
  // 使得伪元素可以基于文本宽度来定位
  display: inline-block;
}

.password-login::after {
  // 伪元素的内容为空
  content: '';
  position: absolute;
  // 根据需要调整这个值以对齐到“码登”下方
  bottom: -2px;
  // 初始位置在元素宽度的中间
  left: 50%;
  // 短横线的宽高
  width: 30px;
  height: 2px;
  background-color: #1890ff;
  transform: translateX(-50%);
}

.register-account {
  position: relative;
  display: inline-block;
}

.register-account::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 50%;
  width: 30px;
  height: 2px;
  background-color: #1890ff;
  transform: translateX(-50%);
}

.title-desc {
  position: fixed;
  top: 36%;
  left: 16%;
  color: #163997;
  font-size: 36px;
  font-weight: bolder;
  min-width: 600px;
  width: 600px;
}
</style>
